import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Avatar,
  Row,
  Col,
  Space,
  Switch,
  Tag,
  Typography,
  Upload,
  Descriptions,
  message,
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  SafetyCertificateOutlined,
  BellOutlined,
  EditOutlined,
  UploadOutlined,
  SaveOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { useLocation } from 'react-router-dom';

const { Title, Text } = Typography;

const Profile: React.FC = () => {
  const [profileForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [settingsForm] = Form.useForm();
  
  const [loading, setLoading] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const [activeSection, setActiveSection] = useState('profile');
  
  const location = useLocation();
  const isPlatformMode = location.pathname.startsWith('/platform');

  // 模拟用户数据
  const [profile, setProfile] = useState({
    username: 'admin',
    email: 'admin@catcloud.com',
    phone: '+86 138-0013-8000',
    realName: '系统管理员',
    department: '技术部',
    position: '平台管理员',
    bio: '负责平台系统管理和维护工作',
    avatar: '',
    loginCount: 1247,
    managedTenants: 156,
    managedUsers: 2847,
    lastLoginTime: '2024-01-20 09:30:00',
    lastLoginIp: '192.168.1.100',
  });

  // 安全设置
  const [securitySettings, setSecuritySettings] = useState({
    enableTwoFactor: true,
    enableEmailNotification: true,
    enableSmsNotification: false,
    enableLoginAlert: true,
  });

  // 处理表单提交
  const handleProfileSubmit = async (values: any) => {
    try {
      setLoading(true);
      setProfile(prev => ({ ...prev, ...values }));
      message.success('个人信息更新成功');
    } catch (error) {
      message.error('更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordSubmit = async (values: any) => {
    try {
      setLoading(true);
      // 模拟密码修改
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('密码修改成功');
      passwordForm.resetFields();
    } catch (error) {
      message.error('密码修改失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSettingsSubmit = async (values: any) => {
    try {
      setLoading(true);
      setSecuritySettings(prev => ({ ...prev, ...values }));
      message.success('安全设置更新成功');
    } catch (error) {
      message.error('更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 头像上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    action: '/api/upload/avatar',
    showUploadList: false,
    beforeUpload: (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片!');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    onChange: (info) => {
      if (info.file.status === 'done') {
        setAvatarUrl(info.file.response?.url || '');
        message.success('头像上传成功');
      } else if (info.file.status === 'error') {
        message.error('头像上传失败');
      }
    },
  };

  return (
    <div>
      {/* 页面标题 */}
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center', color: '#262626' }}>
            <UserOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            个人资料
          </Title>
          <Text type="secondary">管理您的个人信息和账户设置</Text>
        </div>
      </div>

      {/* 个人信息概览 */}
      <Card style={{ marginBottom: 24, borderRadius: 8 }}>
        <Row align="middle" gutter={24}>
          <Col>
            <div style={{ position: 'relative' }}>
              <Avatar         
                size={80} 
                icon={<UserOutlined />} 
                src={avatarUrl || profile.avatar}
                style={{ 
                  backgroundColor: '#1890ff',
                  color: 'white',
                  border: '3px solid #e6f7ff'
                }}
              />
              <Upload {...uploadProps}>
                <Button 
                  size="small" 
                  icon={<UploadOutlined />}
                  style={{ 
                    position: 'absolute',
                    bottom: -5,
                    right: -5,
                    borderRadius: '50%',
                    width: 28,
                    height: 28,
                    padding: 0
                  }}
                />
              </Upload>
            </div>
          </Col>
          <Col flex={1}>
            <div style={{ marginBottom: 8 }}>
              <Text strong style={{ fontSize: '18px', color: '#262626' }}>
                {profile.realName}
              </Text>
              {isPlatformMode && (
                <Tag color="blue" style={{ marginLeft: 12, fontSize: '12px', padding: '4px 8px', borderRadius: 12 }}>
                  平台管理员
                </Tag>
              )}
            </div>
            <div style={{ marginBottom: 4 }}>
              <Text style={{ color: '#8c8c8c', fontSize: '14px' }}>
                {profile.email} • {profile.phone}
              </Text>
            </div>
            <div>
              <Text style={{ color: '#bfbfbf', fontSize: '13px' }}>
                {profile.department} • {profile.position}
              </Text>
            </div>
          </Col>
          <Col>
            <Row gutter={24}>
              <Col style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '20px', fontWeight: 'bold', marginBottom: 4, color: '#1890ff' }}>
                  {profile.loginCount}
                </div>
                <div style={{ fontSize: '12px', color: '#8c8c8c' }}>登录次数</div>
              </Col>
              <Col style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '20px', fontWeight: 'bold', marginBottom: 4, color: '#52c41a' }}>
                  {isPlatformMode ? profile.managedTenants : profile.managedUsers}
                </div>
                <div style={{ fontSize: '12px', color: '#8c8c8c' }}>
                  {isPlatformMode ? '管理租户' : '管理用户'}
                </div>
              </Col>
            </Row>
          </Col>
        </Row>
      </Card>

      <Row gutter={24}>
        {/* 个人信息编辑 */}
        <Col span={12}>
          <Card 
            title={
              <Space>
                <EditOutlined style={{ color: '#52c41a' }} />
                个人信息
              </Space>
            }
            style={{ marginBottom: 24, borderRadius: 8 }}
          >
            <Form
              form={profileForm}
              layout="vertical"
              initialValues={profile}
              onFinish={handleProfileSubmit}
            >
              <Form.Item
                name="realName"
                label="真实姓名"
                rules={[{ required: true, message: '请输入真实姓名' }]}
              >
                <Input placeholder="请输入真实姓名" />
              </Form.Item>

              <Form.Item
                name="email"
                label="邮箱地址"
                rules={[
                  { required: true, message: '请输入邮箱地址' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]}
              >
                <Input placeholder="请输入邮箱地址" />
              </Form.Item>

              <Form.Item
                name="phone"
                label="联系电话"
              >
                <Input placeholder="请输入联系电话" />
              </Form.Item>

              <Form.Item
                name="department"
                label="部门"
              >
                <Input placeholder="请输入部门" />
              </Form.Item>

              <Form.Item
                name="position"
                label="职位"
              >
                <Input placeholder="请输入职位" />
              </Form.Item>

              <Form.Item
                name="bio"
                label="个人简介"
              >
                <Input.TextArea 
                  placeholder="请输入个人简介" 
                  rows={3}
                />
              </Form.Item>

              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  icon={<SaveOutlined />}
                  style={{ borderRadius: 6 }}
                >
                  保存信息
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>

        {/* 密码修改和安全设置 */}
        <Col span={12}>
          {/* 密码修改 */}
          <Card 
            title={
              <Space>
                <LockOutlined style={{ color: '#fa8c16' }} />
                修改密码
              </Space>
            }
            style={{ marginBottom: 24, borderRadius: 8 }}
          >
            <Form
              form={passwordForm}
              layout="vertical"
              onFinish={handlePasswordSubmit}
            >
              <Form.Item
                name="currentPassword"
                label="当前密码"
                rules={[{ required: true, message: '请输入当前密码' }]}
              >
                <Input.Password placeholder="请输入当前密码" />
              </Form.Item>

              <Form.Item
                name="newPassword"
                label="新密码"
                rules={[
                  { required: true, message: '请输入新密码' },
                  { min: 8, message: '密码长度至少8位' },
                ]}
              >
                <Input.Password placeholder="请输入新密码" />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                label="确认密码"
                dependencies={['newPassword']}
                rules={[
                  { required: true, message: '请确认新密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input.Password placeholder="请确认新密码" />
              </Form.Item>

              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  icon={<SaveOutlined />}
                  style={{ borderRadius: 6 }}
                >
                  修改密码
                </Button>
              </Form.Item>
            </Form>
          </Card>

          {/* 安全设置 */}
          <Card 
            title={
              <Space>
                <SafetyCertificateOutlined style={{ color: '#722ed1' }} />
                安全设置
              </Space>
            }
            style={{ borderRadius: 8 }}
          >
            <Form
              form={settingsForm}
              layout="vertical"
              initialValues={securitySettings}
              onFinish={handleSettingsSubmit}
            >
              <Form.Item
                name="enableTwoFactor"
                label="双重验证"
                valuePropName="checked"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>

              <Form.Item
                name="enableEmailNotification"
                label="邮件通知"
                valuePropName="checked"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>

              <Form.Item
                name="enableLoginAlert"
                label="登录提醒"
                valuePropName="checked"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>

              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  icon={<SaveOutlined />}
                  style={{ borderRadius: 6 }}
                >
                  保存设置
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>
      </Row>

      {/* 账户信息 */}
      <Card 
        title={
          <Space>
            <CheckCircleOutlined style={{ color: '#52c41a' }} />
            账户信息
          </Space>
        }
        style={{ marginTop: 24, borderRadius: 8 }}
      >
        <Descriptions column={3} size="small">
          <Descriptions.Item label="用户名">{profile.username}</Descriptions.Item>
          <Descriptions.Item label="账户状态">
            <Tag color="green">正常</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="账户类型">
            {isPlatformMode ? '平台管理员' : '租户用户'}
          </Descriptions.Item>
          <Descriptions.Item label="最后登录时间">{profile.lastLoginTime}</Descriptions.Item>
          <Descriptions.Item label="最后登录IP">{profile.lastLoginIp}</Descriptions.Item>
          <Descriptions.Item label="双重验证">
            <Tag color={securitySettings.enableTwoFactor ? 'green' : 'orange'}>
              {securitySettings.enableTwoFactor ? '已开启' : '未开启'}
            </Tag>
          </Descriptions.Item>
        </Descriptions>
      </Card>
    </div>
  );
};

export default Profile;